package demo.game.chess.common;

import java.util.ArrayList;
import java.util.List;

import demo.game.chess.client.ui.CellLabel;

public class ChessCell extends Position {

	public ChessCell() {

	}

	public ChessCell(final int row, final int column) {
		super(row, column);
	}

	public String getLabel() {
		return CellLabel.getRowLabel(this.row)
				+ CellLabel.getColumnLabel(this.column);
	}

	/**
	 * List of cells leading to the target
	 * according to a horizontal, vertical, or diagonal direction.
	 * 
	 * @param target
	 * @return cell list (target excluded)
	 */
	public final List<ChessCell> getPathTo(final ChessCell target) {
		List<ChessCell> result = new ArrayList<ChessCell>();

		int verticalDirection;
		int horizontalDirection;

		if (isHorizontalAlignWith(target)) {
			// horizontal direction
			verticalDirection = 0;
			horizontalDirection = (target.getColumn() > this.getColumn()) ? 1
					: -1;

		} else if (this.isVerticalAlignWith(target)) {
			// vertical direction
			verticalDirection = (target.getRow() > this.getRow()) ? 1 : -1;
			horizontalDirection = 0;

		} else if (this.isDiagonalAlignWith(target)) {
			// diagonal direction
			verticalDirection = (target.getRow() > this.getRow()) ? 1 : -1;
			horizontalDirection = (target.getColumn() > this.getColumn()) ? 1
					: -1;

		} else {
			return result;
		}
		int i = this.getRow() + verticalDirection;
		int j = this.getColumn() + horizontalDirection;
		while (i >= 0 && i < 8 && j >= 0 && j < 8
				&& (i != target.getRow() || j != target.getColumn())) {
			result.add(new ChessCell(i, j));
			i += verticalDirection;
			j += horizontalDirection;
		}

		return result;
	}

	public boolean isBlack() {
		return (getRow() + getColumn()) % 2 > 0;
	}

	public boolean isDiagonalAlignWith(final ChessCell target) {
		if ((this.getRow() - this.getColumn()) == (target.getRow() - target
				.getColumn())) {
			return true;
		}
		if ((this.getRow() + this.getColumn()) == (target.getRow() + target
				.getColumn())) {
			return true;
		}
		return false;
	}

	public boolean isHorizontalAlignWith(final ChessCell target) {
		return this.getRow() == target.getRow();
	}

	public boolean isVerticalAlignWith(final ChessCell target) {
		return this.getColumn() == target.getColumn();
	}

	@Override
	public String toString() {
		return getLabel() + super.toString();
	}

}
